<template>
  <el-container direction="vertical" class="family-pet"> 
    <!-- 查询面板 -->
    <QueryPanel
      v-model="queryForm"
      :fields="queryFields"
      :actions="queryActions"
      @action="handleQueryAction"
    />

    <!-- 宠物列表 -->
    <DataTable
      :data="petList"
      :loading="loading"
      :columns="tableColumns"
      :pagination="pagination"
      @page-change="handlePageChange"
      @size-change="handleSizeChange"
    >
    
    <!-- 创建时间显示 -->
      <template #created_at="{ row }">
        <span>
          {{ formatDateTime(row.created_at) }}
        </span>
      </template>

      <!-- 健康状态 -->
      <template #health_status="{ row }">
        <el-tag :type="getHealthStatusStyle(row.health_status)">
          {{ getHealthStatusLabel(row.health_status) }}
        </el-tag>
      </template>

      <!-- 疫苗情况 -->
      <template #vaccine_status="{ row }">
        <el-tag :type="getVaccineStatusStyle(row.vaccine_status)">
          {{ getVaccineStatusLabel(row.vaccine_status) }}
        </el-tag>
      </template>

      <!-- 操作按钮 -->
      <template #actions="{ row }">
        <el-button link type="primary" size="small" @click="handleEditPet(row)">
          编辑
        </el-button>
        <el-button link type="danger" size="small" @click="handleDeletePet(row)">
          删除
        </el-button>
      </template>
    </DataTable>

    <!-- 宠物表单对话框 -->
    <FormDialog
      v-model:visible="dialogVisible"
      :title="isEdit ? '编辑宠物' : '添加宠物'"
      :model-value="petForm"
      :fields="petFormFields"
      :rules="petFormRules"
      :loading="saving"
      @submit="savePet"
      @close="resetPetForm"
    />

  </el-container>
</template>

<script setup lang="ts">
import { PetApi, PetInfo, PetQuery } from '@/api/family/pet';
import { reactive, ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import QueryPanel from '@/components/query/QueryPanel.vue' 
import FormDialog from '@/components/page/FormDialog.vue'
import { useUserStore } from '@/store'

const userStore = useUserStore()

// 分页配置
const pagination = reactive({
  page: 1,
  pageSize: 10,
  total: 0
})

// 查询表单
const queryForm = reactive<PetQuery>({
  page: 1,
  pageSize: 10,
  name: '',
  type: '',
  health_status: ''
})

// 查询字段配置
const queryFields = [
  {
    prop: 'name',
    label: '宠物姓名',
    type: 'input',
    placeholder: '请输入宠物姓名'
  },
  {
    prop: 'type',
    label: '宠物类型',
    type: 'select',
    placeholder: '请选择宠物类型',
    options: [
      { label: '狗', value: 'dog' },
      { label: '猫', value: 'cat' },
      { label: '鸟', value: 'bird' },
      { label: '鱼', value: 'fish' },
      { label: '兔子', value: 'rabbit' },
      { label: '其他', value: 'other' }
    ]
  },
  {
    prop: 'health_status',
    label: '健康状态',
    type: 'select',
    placeholder: '请选择健康状态',
    options: [
      { label: '健康', value: 'healthy' },
      { label: '需关注', value: 'need_attention' },
      { label: '治疗中', value: 'under_treatment' }
    ]
  }
]

// 查询操作按钮
const queryActions = [
  { name: 'search', label: '查询', type: 'primary' as const },
  { name: 'reset', label: '重置', type: '' as const },
  { name: 'add', label: '添加宠物', type: 'success' as const }
]

// 表格列配置
const tableColumns = [
  { prop: 'name', label: '宠物姓名', width: 120 },
  { prop: 'type', label: '宠物类型', width: 100 },
  { prop: 'breed', label: '品种', width: 120 },
  { prop: 'age', label: '年龄(岁)', width: 100 },
  { prop: 'health_status', label: '健康状态', slot: 'health_status', width: 100 },
  { prop: 'vaccine_status', label: '疫苗情况', slot: 'vaccine_status', width: 100 },
  { prop: 'last_checkup', label: '上次体检', width: 120 },
  { prop: 'total_expense', label: '累计花销(元)', width: 120 },
  { prop: 'created_at', label: '创建时间', slot: 'created_at', width: 200 },
]

// 宠物表单字段配置
const petFormFields = [
  {
    prop: 'name',
    label: '宠物姓名',
    type: 'input',
    placeholder: '请输入宠物姓名',
    rules: { required: true, message: '请输入宠物姓名', trigger: 'blur' }
  },
  {
    prop: 'type',
    label: '宠物类型',
    type: 'select',
    placeholder: '请选择宠物类型',
    options: [
      { label: '狗', value: 'dog' },
      { label: '猫', value: 'cat' },
      { label: '鸟', value: 'bird' },
      { label: '鱼', value: 'fish' },
      { label: '兔子', value: 'rabbit' },
      { label: '其他', value: 'other' }
    ],
    rules: { required: true, message: '请选择宠物类型', trigger: 'change' }
  },
  {
    prop: 'breed',
    label: '品种',
    type: 'input',
    placeholder: '请输入宠物品种'
  },
  {
    prop: 'age',
    label: '年龄(岁)',
    type: 'number',
    placeholder: '请输入宠物年龄',
    props: {
      min: 0,
      step: 0.1,
      controls: false
    },
    rules: { required: true, message: '请输入宠物年龄', trigger: 'blur' }
  },
  {
    prop: 'gender',
    label: '性别',
    type: 'select',
    placeholder: '请选择宠物性别',
    options: [
      { label: '公', value: 'male' },
      { label: '母', value: 'female' }
    ],
    rules: { required: true, message: '请选择宠物性别', trigger: 'change' }
  },
  {
    prop: 'health_status',
    label: '健康状态',
    type: 'select',
    placeholder: '请选择健康状态',
    options: [
      { label: '健康', value: 'healthy' },
      { label: '需关注', value: 'need_attention' },
      { label: '治疗中', value: 'under_treatment' }
    ],
    rules: { required: true, message: '请选择健康状态', trigger: 'change' }
  },
  {
    prop: 'vaccine_status',
    label: '疫苗情况',
    type: 'select',
    placeholder: '请选择疫苗情况',
    options: [
      { label: '已接种', value: 'vaccinated' },
      { label: '待接种', value: 'pending' },
      { label: '未接种', value: 'not_vaccinated' }
    ],
    rules: { required: true, message: '请选择疫苗情况', trigger: 'change' }
  },
  {
    prop: 'last_checkup',
    label: '上次体检时间',
    type: 'date',
    placeholder: '请选择上次体检时间',
    props: {
      format: 'YYYY-MM-DD',
      valueFormat: 'YYYY-MM-DD'
    }
  },
  {
    prop: 'total_expense',
    label: '累计医疗花销(元)',
    type: 'number',
    placeholder: '请输入累计医疗花销',
    props: {
      min: 0,
      step: 0.01,
      controls: false
    }
  },
  {
    prop: 'notes',
    label: '备注信息',
    type: 'textarea',
    placeholder: '请输入备注信息',
    props: {
      rows: 3
    }
  }
]

// 宠物表单验证规则
const petFormRules = {}

// 数据状态
const loading = ref(false)
const saving = ref(false)
const dialogVisible = ref(false)
const isEdit = ref(false)
const currentPetId = ref<number | null>(null)
const petList = ref<PetInfo[]>([])

// 获取健康状态标签
const getHealthStatusLabel = (status: string) => {
  console.log("已经调用",status)
  const statusMap: Record<string, string> = {
    'healthy': '健康',
    'need_attention': '需关注',
    'under_treatment': '治疗中'
  }
  return statusMap[status] || status
}

// 获取健康状态样式
const getHealthStatusStyle = (status: string) => {
  const styleMap: Record<string, string> = {
    'healthy': 'success',
    'need_attention': 'warning',
    'under_treatment': 'danger'
  }
  return styleMap[status] || 'info'
}

// 获取疫苗状态标签
const getVaccineStatusLabel = (status: string) => {
  const statusMap: Record<string, string> = {
    'vaccinated': '已接种',
    'pending': '待接种',
    'not_vaccinated': '未接种'
  }
  return statusMap[status] || status
}

// 获取疫苗状态样式
const getVaccineStatusStyle = (status: string) => {
  const styleMap: Record<string, string> = {
    'vaccinated': 'success',
    'pending': 'warning',
    'not_vaccinated': 'danger'
  }
  return styleMap[status] || 'info'
}

// 保存宠物
const savePet = async () => {
  try {
    saving.value = true
    if (isEdit.value) {
      // 编辑模式
      if (currentPetId.value) {
        await PetApi.updatePet(currentPetId.value, petForm)
        ElMessage.success('更新成功')
      }
    } else {
      // 新增模式
      await PetApi.createPet(petForm)
      ElMessage.success('新增成功')
    }
    dialogVisible.value = false
    loadPets() // 刷新列表
  } catch (error) {
    ElMessage.error(isEdit.value ? '更新失败' : '新增失败')
  } finally {
    saving.value = false
  }
}

// 重置宠物表单
const resetPetForm = () => {
  Object.assign(petForm, {
    id: null,
    name: '',
    type: '',
    breed: '',
    age: 0,
    gender: '',
    health_status: 'healthy',
    vaccine_status: 'vaccinated',
    last_checkup: '',
    total_expense: 0,
    notes: '',
    user_id: userStore.userInfo.id,
    family_id: 1
  })
}

// 添加宠物
const handleAddPet = () => {
  isEdit.value = false
  currentPetId.value = null
  resetPetForm()
  dialogVisible.value = true
}

// 查询方法
const loadPets = async () => {
  try {
    loading.value = true
    const response = await PetApi.getPetList(queryForm)
    
    petList.value = response.data || []
    pagination.total = response.total || 0
    pagination.pageSize = response.page_size || pagination.pageSize
  } catch (error) {
    ElMessage.error('获取宠物列表失败')
  } finally {
    loading.value = false
  }
}

const handlePageChange = (page: number) => {
  queryForm.page = page
  loadPets()
}

const handleSizeChange = (size: number) => {
  queryForm.pageSize = size
  queryForm.page = 1
  loadPets()
}

// 时间格式化函数
const formatDateTime = (dateString: string): string => {
  if (!dateString) return '';
  try {
    const formatDate = new Date(dateString).toLocaleString('zh-CN', {
      year: 'numeric',
      month: '2-digit',
      day: '2-digit',
      hour: '2-digit',
      minute: '2-digit',
      second: '2-digit'
    }).replace(/\//g, '-');
    return formatDate;
  } catch (error) {
    return dateString;
  }
}

const handleQueryAction = (action: string) => {
  switch (action) {
    case 'search':
      queryForm.page = 1
      loadPets()
      break
    case 'reset':
      Object.assign(queryForm, {
        name: '',
        type: '',
        health_status: '',
        page: 1,
        pageSize: 10
      })
      loadPets()
      break
    case 'add':
      handleAddPet()
      break
  }
}

// 宠物表单
const petForm = reactive<Partial<PetInfo>>({
  id: null,
  name: '',
  type: '',
  breed: '',
  age: 0,
  gender: '',
  health_status: 'healthy',
  vaccine_status: 'vaccinated',
  last_checkup: '',
  total_expense: 0,
  notes: '',
  user_id: 0,
  family_id: 1
})

const handleEditPet = (pet: PetInfo) => {
  isEdit.value = true
  currentPetId.value = pet.id
  Object.assign(petForm, {
    id: pet.id,
    name: pet.name,
    type: pet.type,
    breed: pet.breed,
    age: pet.age,
    gender: pet.gender,
    health_status: pet.health_status,
    vaccine_status: pet.vaccine_status,
    last_checkup: pet.last_checkup,
    total_expense: pet.total_expense,
    notes: pet.notes,
    user_id: pet.user_id,
    family_id: pet.family_id
  })
  dialogVisible.value = true
}

const handleDeletePet = async (pet: PetInfo) => {
  try {
    await ElMessageBox.confirm(`确定要删除宠物"${pet.name}"吗？`, '提示', {
      type: 'warning'
    })
    await PetApi.deletePet(pet.id)
    ElMessage.success('删除成功')
    loadPets()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
    }
  }
}

onMounted(() => {
  loadPets()
})
</script>

<style scoped>
.family-pet {
  padding: 20px;
}
</style>